<template>
  <div class="student-manage">
    <h1>学生管理</h1>
    <p>学校端学生管理页面</p>
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>学生管理</h2>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="queryForm" inline>
        <el-form-item label="账号">
          <el-input
            v-model="queryForm.account"
            placeholder="请输入学生账号"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model="queryForm.name"
            placeholder="请输入学生姓名"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          <el-button type="success" :icon="Plus" @click="handleAdd">添加学生</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="hover">
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="studentList"
          stripe
          border
          style="width: 100%"
          :height="tableHeight"
        >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="account" label="账号" width="120" align="center" />
        <el-table-column prop="name" label="姓名" width="100" align="center" />
        <el-table-column prop="phone" label="手机号" width="130" align="center" />
        <el-table-column prop="email" label="邮箱" width="180" align="center" />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.gender === 1 ? 'primary' : 'danger'" size="small">
              {{ row.gender === 1 ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="avatar" label="头像" width="80" align="center">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" :size="40">
              <el-icon><Avatar /></el-icon>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            <div class="time-display">
              <span class="relative-time" :title="formatDateTime(row.createTime)">
                {{ formatRelativeTime(row.createTime) }}
              </span>
              <div class="exact-time">{{ formatDateTime(row.createTime) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间" width="180" align="center">
          <template #default="{ row }">
            <div class="time-display">
              <span class="relative-time" :title="formatDateTime(row.updateTime)">
                {{ formatRelativeTime(row.updateTime) }}
              </span>
              <div class="exact-time">{{ formatDateTime(row.updateTime) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[5,10, 20, 50, 100]"
          :total="pagination.count"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="studentFormRef"
        :model="studentForm"
        :rules="studentRules"
        label-width="100px"
      >
        <el-form-item label="账号" prop="account">
          <el-input v-model="studentForm.account" placeholder="请输入学生账号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="studentForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="studentForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="studentForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <div class="avatar-upload-container">
            <!-- 头像预览 -->
            <div class="avatar-preview">
              <el-avatar :src="studentForm.avatar" :size="80" v-if="studentForm.avatar">
                <el-icon><Avatar /></el-icon>
              </el-avatar>
              <div v-else class="avatar-placeholder">
                <el-icon size="40"><Avatar /></el-icon>
                <span>暂无头像</span>
              </div>
            </div>

            <!-- 上传按钮和URL输入 -->
            <div class="avatar-controls">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                action="#"
                :http-request="uploadAvatar"
                :disabled="uploadLoading"
              >
                <el-button size="small" type="primary" :loading="uploadLoading" :disabled="uploadLoading">
                  <el-icon v-if="!uploadLoading"><Upload /></el-icon>
                  {{ uploadLoading ? '上传中...' : '上传头像' }}
                </el-button>
              </el-upload>

              <div class="avatar-url-input">
                <el-input
                  v-model="studentForm.avatar"
                  placeholder="或直接输入头像URL"
                  size="small"
                  @input="handleAvatarUrlChange"
                />
              </div>

              <el-button
                size="small"
                type="danger"
                plain
                @click="clearAvatar"
                v-if="studentForm.avatar"
              >
                清除头像
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 学校端学生管理页面
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Avatar, Upload } from '@element-plus/icons-vue'
import { queryStudentList, addStudent, updateStudent, deleteStudent } from '@/api/school'
import request from '@/utils/request'

// 加载状态
const loading = ref(false)

// 表格高度计算
const tableHeight = computed(() => {
  // 基础高度：页面高度 - 标题 - 搜索区域 - 分页器 - 各种间距
  // 这里设置一个合适的固定高度，确保表格能够显示滚动条
  return 'calc(100vh - 320px)'
})

// 查询表单
const queryForm = reactive({
  account: '',
  name: ''
})

// 分页参数
const pagination = reactive({
  page: 1,
  limit: 5,
  count: 0
})

// 学生列表数据
const studentList = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加学生')
const isEdit = ref(false)
const studentFormRef = ref(null)

// 头像上传状态
const uploadLoading = ref(false)

// 学生表单数据
const studentForm = reactive({
  id: null,
  account: '',
  name: '',
  phone: '',
  email: '',
  gender: 1,
  avatar: ''
})

// 表单验证规则
const studentRules = {
  account: [
    { required: true, message: '请输入学生账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

// 获取学生列表
const getStudentList = async () => {
  loading.value = true
  try {
    const params = {
      account: queryForm.account,
      name: queryForm.name,
      page: pagination.page,
      limit: pagination.limit
    }
    const res = await queryStudentList(params)
    if (res.code === 0) {
      // 确保每个学生对象的id字段是数字类型，兼容后端返回字符串或数字
      studentList.value = (res.data || []).map(student => {
        // 处理id字段，确保转换为数字类型以匹配后端Long类型
        let studentId = null
        if (student.id !== null && student.id !== undefined && student.id !== '') {
          const parsed = typeof student.id === 'number' ? student.id : parseInt(student.id, 10)
          studentId = isNaN(parsed) ? null : parsed
        }

        if (!studentId) {
          console.warn('学生数据缺少有效ID:', student)
        }

        return {
          ...student,
          id: studentId
        }
      })
      console.log('获取学生列表成功，数量:', studentList.value.length)
      if (studentList.value.length > 0) {
        console.log('第一个学生数据:', studentList.value[0])
        console.log('第一个学生的ID:', studentList.value[0].id, '类型:', typeof studentList.value[0].id)
      }
      pagination.count = res.count || 0
    } else {
      ElMessage.error(res.msg || '获取学生列表失败')
    }
  } catch (error) {
    ElMessage.error('获取学生列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getStudentList()
}

// 重置
const handleReset = () => {
  queryForm.account = ''
  queryForm.name = ''
  pagination.page = 1
  getStudentList()
}

// 每页条数改变
const handleSizeChange = (val) => {
  pagination.limit = val
  pagination.page = 1
  getStudentList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.page = val
  getStudentList()
}

// 添加学生
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加学生'
  dialogVisible.value = true
  resetForm()
}

// 编辑学生
const handleEdit = (row) => {
  console.log('点击编辑，原始数据:', row)

  if (!row.id && row.id !== 0) {
    ElMessage.error('学生ID不存在，无法编辑')
    console.error('编辑失败：学生数据缺少id字段', row)
    return
  }

  // 确保id是有效的数字类型
  const studentId = typeof row.id === 'number' ? row.id : parseInt(row.id, 10)
  if (isNaN(studentId)) {
    ElMessage.error('学生ID格式错误，无法编辑')
    console.error('编辑失败：ID无法转换为数字', row.id)
    return
  }

  isEdit.value = true
  dialogTitle.value = '编辑学生'
  dialogVisible.value = true

  // 确保id被正确复制为数字类型
  Object.assign(studentForm, {
    ...row,
    id: studentId
  })
  console.log('编辑学生，ID:', studentForm.id, '类型:', typeof studentForm.id)
}

// 删除学生
const handleDelete = (row) => {
  console.log('点击删除，原始数据:', row)

  if (!row.id && row.id !== 0) {
    ElMessage.error('学生ID不存在，无法删除')
    console.error('删除失败：学生数据缺少id字段', row)
    return
  }

  // 确保id是有效的数字类型
  const studentId = typeof row.id === 'number' ? row.id : parseInt(row.id, 10)
  if (isNaN(studentId)) {
    ElMessage.error('学生ID格式错误，无法删除')
    console.error('删除失败：ID无法转换为数字', row.id)
    return
  }

  console.log('准备删除学生，ID:', studentId, '类型:', typeof studentId)

  ElMessageBox.confirm(
    `确定要删除学生 "${row.name}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      console.log('调用删除API，传递ID:', studentId)
      const res = await deleteStudent(studentId)
      if (res.code === 0) {
        ElMessage.success('删除成功')
        getStudentList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
      console.error('删除API调用失败:', error)
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!studentFormRef.value) return

  await studentFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构建提交数据
        const submitData = {
          account: studentForm.account,
          name: studentForm.name,
          phone: studentForm.phone,
          email: studentForm.email,
          gender: studentForm.gender,
          avatar: studentForm.avatar
        }

        // 编辑时需要传递id，确保类型为数字以匹配后端Long类型
        if (isEdit.value) {
          if (!studentForm.id && studentForm.id !== 0) {
            ElMessage.error('学生ID不存在，无法更新')
            console.error('更新失败：缺少学生ID', studentForm)
            return
          }

          // 确保id是有效的数字类型
          const studentId = typeof studentForm.id === 'number' ? studentForm.id : parseInt(studentForm.id, 10)
          if (isNaN(studentId)) {
            ElMessage.error('学生ID格式错误，无法更新')
            console.error('更新失败：ID无法转换为数字', studentForm.id)
            return
          }

          submitData.id = studentId
          console.log('提交更新，ID:', submitData.id, '类型:', typeof submitData.id)
        }

        const res = isEdit.value
          ? await updateStudent(submitData)
          : await addStudent(submitData)

        if (res.code === 0) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
          dialogVisible.value = false
          getStudentList()
        } else {
          ElMessage.error(res.msg || (isEdit.value ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
        console.error(error)
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
  if (studentFormRef.value) {
    studentFormRef.value.clearValidate()
  }
}

// 重置表单
const resetForm = () => {
  studentForm.id = null
  studentForm.account = ''
  studentForm.name = ''
  studentForm.phone = ''
  studentForm.email = ''
  studentForm.gender = 1
  studentForm.avatar = ''
}

// 头像上传相关方法
const beforeAvatarUpload = (file) => {
  // 与后端保持一致的文件格式验证：.jpg, .png, .jpeg, .gif
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
  const isValidType = allowedTypes.includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isValidType) {
    ElMessage.error('头像只能是 JPG/PNG/JPEG/GIF 格式!')
    console.error('不支持的文件类型:', file.type)
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    console.error('文件过大:', file.size / 1024 / 1024, 'MB')
    return false
  }

  console.log('文件验证通过:', {
    name: file.name,
    type: file.type,
    size: (file.size / 1024 / 1024).toFixed(2) + 'MB'
  })

  return true
}

const uploadAvatar = async (options) => {
  const file = options.file
  uploadLoading.value = true

  try {
    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', file)

    console.log('开始上传头像文件:', {
      name: file.name,
      type: file.type,
      size: (file.size / 1024 / 1024).toFixed(2) + 'MB'
    })

    // 使用项目的request工具调用后端上传接口
    const result = await request.post('/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    console.log('上传响应:', result)

    // 上传成功，设置头像URL
    studentForm.avatar = result.data
    ElMessage.success('头像上传成功')
    console.log('头像URL已设置:', result.data)

  } catch (error) {
    ElMessage.error('头像上传失败')
    console.error('上传异常:', error)
  } finally {
    uploadLoading.value = false
  }
}

const handleAvatarSuccess = (response) => {
  // 如果有真实的上传接口，在这里处理成功回调
  console.log('头像上传成功', response)
}

const handleAvatarError = (error) => {
  ElMessage.error('头像上传失败')
  console.error('头像上传失败', error)
}

const handleAvatarUrlChange = () => {
  // URL输入变化时的处理
  console.log('头像URL已更新:', studentForm.avatar)
}

const clearAvatar = () => {
  studentForm.avatar = ''
  ElMessage.success('头像已清除')
}

// 时间格式化工具函数
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''

  try {
    const date = new Date(dateTimeStr)
    if (isNaN(date.getTime())) return dateTimeStr

    const now = new Date()
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    // 如果是今年，不显示年份
    if (year === now.getFullYear()) {
      return `${month}-${day} ${hours}:${minutes}`
    }

    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('时间格式化错误:', error)
    return dateTimeStr
  }
}

const formatRelativeTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''

  try {
    const date = new Date(dateTimeStr)
    if (isNaN(date.getTime())) return dateTimeStr

    const now = new Date()
    const diffMs = now.getTime() - date.getTime()
    const diffSeconds = Math.floor(diffMs / 1000)
    const diffMinutes = Math.floor(diffSeconds / 60)
    const diffHours = Math.floor(diffMinutes / 60)

    // 未来时间显示为具体时间
    if (diffMs < 0) {
      return '未来时间'
    }

    // 今天的时间
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const dateOnly = new Date(date)
    dateOnly.setHours(0, 0, 0, 0)
    const daysDiff = Math.floor((today.getTime() - dateOnly.getTime()) / (1000 * 60 * 60 * 24))

    // 相对时间显示
    if (daysDiff === 0) {
      // 今天
      if (diffSeconds < 60) {
        return '刚刚'
      } else if (diffMinutes < 60) {
        return `${diffMinutes}分钟前`
      } else {
        return `${diffHours}小时前`
      }
    } else if (daysDiff === 1) {
      return '昨天'
    } else if (daysDiff === 2) {
      return '前天'
    } else if (daysDiff < 7) {
      return `${daysDiff}天前`
    } else if (daysDiff < 30) {
      const weeks = Math.floor(daysDiff / 7)
      return `${weeks}周前`
    } else if (daysDiff < 365) {
      const months = Math.floor(daysDiff / 30)
      return `${months}个月前`
    } else {
      const years = Math.floor(daysDiff / 365)
      return `${years}年前`
    }
  } catch (error) {
    console.error('相对时间格式化错误:', error)
    return formatDateTime(dateTimeStr)
  }
}

// 页面加载时获取数据
onMounted(() => {
  getStudentList()
})
</script>

<style scoped>
.student-manage {
  padding: 20px;
  padding: 10px 20px 20px 20px; /* 调整padding，底部减少以配合滚动 */
  background-color: #f5f7fa;
  min-height: calc(100vh - 80px);
  max-height: calc(100vh - 80px); /* 设置最大高度，超出时显示滚动条 */
  overflow-y: auto; /* 垂直方向自动显示滚动条 */
  overflow-x: hidden; /* 隐藏水平滚动条 */
  display: flex;
  flex-direction: column;

  /* 自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

/* Webkit浏览器滚动条样式 */
.student-manage::-webkit-scrollbar {
  width: 8px;
}

.student-manage::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.student-manage::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.student-manage::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

.page-header {
  margin-bottom: 10px; /* 进一步减少页面标题的底部间距 */
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.search-card {
  margin-bottom: 10px; /* 进一步减少搜索卡片的底部间距 */
}


.table-card {
  background-color: #fff;
  margin-bottom: 20px; /* 为分页器留出空间 */
  flex: 1; /* 让表格卡片占据剩余空间 */
  display: flex;
  flex-direction: column;
  min-height: 0; /* 允许flex子元素缩小 */
  overflow: hidden; /* 防止内容溢出 */
}

.table-wrapper {
  flex: 1;
  overflow: hidden;
}




.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px; /* 减少顶部间距，让分页器更靠近表格 */
  margin-bottom: 20px; /* 减少底部边距，配合滚动布局 */
  padding: 15px 0; /* 适当的内边距 */
  flex-shrink: 0; /* 防止分页器被压缩 */
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 头像上传样式 */
.avatar-upload-container {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.avatar-preview {
  flex-shrink: 0;
}

.avatar-placeholder {
  width: 80px;
  height: 80px;
  border: 2px dashed #dcdfe6;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 12px;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.avatar-placeholder:hover {
  border-color: #409eff;
  color: #409eff;
}

.avatar-controls {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.avatar-url-input {
  width: 100%;
}



/* 时间显示样式 */
.time-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.relative-time {
  font-weight: 500;
  color: #409eff;
  font-size: 13px;
  cursor: help;
}

.exact-time {
  font-size: 11px;
  color: #909399;
  line-height: 1.2;
}

/* 响应式优化 */
@media screen and (max-width: 768px) {
  .student-manage {
    padding: 8px 15px 15px 15px; /* 移动端减少padding，配合滚动布局 */
    max-height: calc(100vh - 60px); /* 移动端调整最大高度 */
  }

  .pagination-container {
    justify-content: center; /* 移动端居中显示分页器 */
    margin-bottom: 15px; /* 移动端减少底部边距，配合滚动 */
    padding: 15px 0;
  }

  .avatar-upload-container {
    flex-direction: column;
    gap: 15px;
  }

  .avatar-preview {
    align-self: center;
  }

  .time-display {
    gap: 1px;
  }

  .relative-time {
    font-size: 12px;
  }

  .exact-time {
    font-size: 10px;
  }
}
</style>
